﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>角色管理</title>
    <link rel="stylesheet" href="../../assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="../../assets/module/admin.css?v=318"/>
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript" src="../../assets/js/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="../../assets/js/config.js"></script>
    <script type="text/javascript" src="../../assets/js/auth.js"></script></head>
<body>
<!-- 正文开始 -->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <!-- 表格工具栏 -->
            <form class="layui-form toolbar" id="searchData">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">角色名:</label>
                        <div class="layui-input-inline">
                            <input name="name" class="layui-input" placeholder="输入角色名"/>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">角色代码:</label>
                        <div class="layui-input-inline">
                            <input name="perms" class="layui-input" placeholder="输入角色代码"/>
                        </div>
                </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">备&emsp;注:</label>
                        <div class="layui-input-inline">
                            <input name="remark" class="layui-input" placeholder="输入备注"/>
                        </div>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn" lay-filter="roleTbSearch" lay-submit>
                            <i class="layui-icon">&#xe615;</i>搜索
                        </button>
                    </div>
                    <div class="layui-inline">&emsp;
                        <button class="layui-btn icon-btn layui-btn-danger" lay-filter="roleTbClear" lay-submit>
                            <i class="layui-icon">&#xe666;</i>清空
                        </button>
                    </div>
                </div>
            </form>
            <!-- 数据表格 -->
            <table id="roleTable" lay-filter="roleTable"></table>
        </div>
    </div>
</div>

<!-- 表格操作列 -->
<script type="text/html" id="roleTbBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="auth">权限分配</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="roleEditDialog">
    <form id="roleEditForm" lay-filter="roleEditForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">角色名:</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入角色名" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label layui-form-required">角色代码:</label>
            <div class="layui-input-block">
                <input name="perms" placeholder="请输入角色代码" class="layui-input"
                       lay-verType="tips" lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注:</label>
            <div class="layui-input-block">
                <textarea name="remark" placeholder="请输入备注" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn" lay-filter="roleEditSubmit" lay-submit>保存</button>
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
        </div>
    </form>
</script>
<!-- js部分 -->
<script type="text/javascript" src="../../assets/libs/layui/layui.js"></script>
<script type="text/javascript" src="../../assets/js/common.js?v=318"></script>
<script>
    layui.use(['layer', 'form', 'table', 'util', 'admin', 'zTree'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var admin = layui.admin;
        var count=0;
        var insTb="";

        //渲染表格
        var renderTable = function () {
            layer.load(2);
            let requestData={"name":'',"perms":'',"remark":'',"page":1,"limit":10};
            $.ajax({
                type: 'get',
                url: basePath+'/admin/roles/index',
                data: requestData,
                dataType: 'json',
                beforeSend: function (XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("token", auth.token);
                },
                success: function (res) {
                    count=res.total;
                    renderTable(res.data);
                }
            });

            // 渲染表格
            var renderTable = function (data) {
                layer.load(2);
                insTb = table.render({
                    elem: '#roleTable',
                    url: basePath+'/admin/roles/index',
                    page: true,
                    toolbar: ['<p>',
                        '<button lay-event="add" class="layui-btn layui-btn-sm icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>&nbsp;',
                        '<button lay-event="del" class="layui-btn layui-btn-sm layui-btn-danger icon-btn"><i class="layui-icon">&#xe640;</i>删除</button>',
                        '</p>'].join(''),
                    cellMinWidth: 100,
                    cols: [[
                        {type: 'checkbox'},
                        {type: 'numbers',field: 'id'},
                        {field: 'name', title: '角色名', sort: true},
                        {field: 'perms', title: '角色代码', sort: true},
                        {field: 'remark', title: '备注', sort: true},
                        {
                            field: 'gmtCreate', title: '创建时间', templet: function (d) {
                                return util.toDateString(d.gmtCreate);
                            }, sort: true
                        },
                        {title: '操作', toolbar: '#roleTbBar', align: 'center', width: 200, minWidth: 200}
                    ]] //数据渲染完的回调
                    ,done: function () {
                        //清空本地记录的 token，并跳转到登入页
                        layer.closeAll('loading');
                    }
                });
            }
        };

        renderTable();
        /* 表格搜索 */
        form.on('submit(roleTbSearch)', function (data) {
            insTb.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        /* 表格清空*/
        form.on('submit(roleTbClear)', function (data) {
            $("#searchData")[0].reset();
            intab.reload({where: data.field, page: {curr: 1}});
            return false;
        });

        /* 表格工具条点击事件 */
        table.on('tool(roleTable)', function (obj) {
            if (obj.event === 'edit') { // 修改
                showEditModel(obj.data);
            } else if (obj.event === 'del') { // 删除
                doDel(obj);
            } else if (obj.event === 'auth') {  // 权限管理
                showPermModel(obj.data.id);
            }
        });

        /* 表格头工具栏点击事件 */
        table.on('toolbar(roleTable)', function (obj) {
            if (obj.event === 'add') { // 添加
                showEditModel();
            } else if (obj.event === 'del') { // 删除
                var checkRows = table.checkStatus('roleTable');
                if (checkRows.data.length === 0) {
                    layer.msg('请选择要删除的数据', {icon: 2});
                    return;
                }
                var ids = checkRows.data.map(function (d) {
                    return d.roleId;
                });
                doDel({ids: ids});
            }
        });

        /* 显示表单弹窗 */
        function showEditModel(mData) {
            admin.open({
                type: 1,
                title: (mData ? '修改' : '添加') + '角色',
                content: $('#roleEditDialog').html(),
                success: function (layero, dIndex) {
                    // 回显表单数据
                    form.val('roleEditForm', mData);
                    // 表单提交事件
                    form.on('submit(roleEditSubmit)', function (data) {
                        var loadIndex = layer.load(2);
                        $.ajax({
                            type: "post",
                            url: basePath + '/admin/roles/saveOrUpdate',
                            data: data.field,
                            async: false,
                            dataType: "json",
                            //这里是重点
                            beforeSend: function (XMLHttpRequest) {
                                XMLHttpRequest.setRequestHeader("token", auth.token);
                            },
                            success: function (res) {
                                if(res.code=="00000"){
                                    layer.msg(res.msg, {icon: 1});
                                    insTb.reload({where: '', page: {curr: 1}});
                                }else{
                                    layer.msg(res.msg, {icon: 2});
                                }
                                layer.close(dIndex);
                            },
                            error: function (error) {
                                console.log(error);
                            }
                        });
                        layer.close(loadIndex);
                        return false;
                    });
                }
            });
        }

        /* 删除 */
        function doDel(obj) {
            layer.confirm('确定要删除选中数据吗？', {
                skin: 'layui-layer-admin',
                shade: .1
            }, function (i) {
                layer.close(i);
                var loadIndex = layer.load(2);
                $.ajax({
                    type: "post",
                    url: basePath + '/admin/roles/deleteById',
                    data: {"id": obj.data.id},
                    async: false,
                    dataType: "json",
                    //这里是重点
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("token", auth.token);
                    },
                    success: function (res) {
                        if(res.code=="00000"){
                            layer.msg(res.msg, {icon: 1});
                            insTb.reload({where: '', page: {curr: 1}});
                        }else{
                            layer.msg(res.msg, {icon: 2});
                        }
                        layer.close(loadIndex);
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
            });
        }

        var setting={
            view: {
                selectedMulti:true, //设置是否能够同时选中多个节点
                showIcon: true, //设置是否显示节点图标
                showLine: true,  //设置是否显示节点与节点之间的连线
                showTitle:true  //设置是否显示节点的title提示信息
            },
            check: {enable: true}, //设置是否显示checkbox复选框
            data: {simpleData:
                    {
                        enable: true // 设置是否启用简单数据格式（zTree支持标准数据格式跟简单数据格式，上面例子中是标准数据格式）
                       ,idKey:"id"  //设置启用简单数据格式时id对应的属性名称
                       ,pidKey:"pId" //设置启用简单数据格式时parentId对应的属性名称,ztree根据id及pid层级关系构建树结构
                    }
            },
            callback: {
                onClick: zOnClick //定义节点单击事件回调函数
               ,onRightClick: OnRightClick//定义节点右键单击事件回调函数
            }
        };

        //父节点双击展开
        function dblClickExpand(treeId, treeNode) {
            alert("我是点击展开")
            return treeNode.level >= 0;
        }

        //子节点点击用于显示细节点中的内容
        function zOnClick(event, treeId, treeNode) {
           alert("子节点")
        };

        // 点击右键回调
        function OnRightClick(){
            alert("点击右键回调")
        }

        /* 权限管理 */
        function showPermModel(roleId) {
            admin.open({
                title: '角色权限分配',
                btn: ['保存', '取消'],
                content: '<ul id="roleAuthTree" class="ztree"></ul>',
                success: function (layero, dIndex) {
                    var loadIndex = layer.load(2);
                    $.get(basePath + '/admin/roles/authRole', {id: roleId}, function (res) {
                        layer.close(loadIndex);
                        if ("00000" === res.code) {
                            $.fn.zTree.init($('#roleAuthTree'), setting, res.data);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'json');
                    // 超出一定高度滚动
                    $(layero).children('.layui-layer-content').css({'max-height': '300px', 'overflow': 'auto'});
                },
                yes: function (dIndex) {
                    var insTree = $.fn.zTree.getZTreeObj('roleAuthTree');
                    var checkedRows = insTree.getCheckedNodes(true);
                    var ids = [];
                    for (var i = 0; i < checkedRows.length; i++) {
                        ids.push(checkedRows[i].id);
                    }
                    var loadIndex = layer.load(2);
                    $.ajax({
                        type: "post",
                        url: basePath + '/admin/roleMenu/updateAuth',
                        data: {"roleId": roleId,"authId":ids.join(',')},
                        async: false,
                        dataType: "json",
                        //这里是重点
                        beforeSend: function (XMLHttpRequest) {
                            XMLHttpRequest.setRequestHeader("token", auth.token);
                        },
                        success: function (res) {
                            if(res.code=="00000"){
                                layer.msg(res.msg, {icon: 1});
                                insTb.reload({where: '', page: {curr: 1}});
                            }else{
                                layer.msg(res.msg, {icon: 2});
                            }
                            layer.close(loadIndex);
                            layer.close(dIndex);
                        },
                        error: function (error) {
                            console.log(error);
                        }
                    });
                }
            });
        }

    });
</script>
</body>
</html>
